using System;
using System.Drawing;
using System.Collections;

public class ImageSplitter:IDisposable
{
	public ArrayList streamList;
	private int _imageW, _imageH;
	private System.Drawing.Image ImgToSplit;

	public ImageSplitter (string fileName) {
		ImgToSplit = System.Drawing.Image.FromFile(fileName);
		
		this._imageW = ImgToSplit.Width;
		this._imageH = ImgToSplit.Height;
	}
	
	public void SplitNow(int noHor, int noVer) 	{
		streamList = new ArrayList(); // (noHor * noVer);
//		int counter = 1;
        Point P1 = new Point();
        Point P2 = new Point();
        int encX = this._imageW / noHor;
        int encY = this._imageH / noVer;

        for (int j = 0; j < noVer; j++) {
			for (int i = 0; i < noHor; i++) {
            	P1.X = encX * i;
                P1.Y = encY * j;
                P2.X = (encX * i) + encX;
                P2.Y = (encY * j) + encY;
	            SplitHere(P1, P2);
            }
		}
	}
	
	#region Split operation
	private void SplitHere (Point P1, Point P2) {
		System.Drawing.Bitmap bmpResult;
		Size size = GetRectangleSize(P1, P2);
		bmpResult = new Bitmap(size.Width, size.Height);
		Graphics g = Graphics.FromImage(bmpResult);
		g.DrawImage(ImgToSplit, 0, 0, GetSelectedRectangle(P1, P2), GraphicsUnit.Pixel);
		g.Dispose();

		System.Drawing.Image imgResult = (System.Drawing.Image)bmpResult;		
		System.IO.MemoryStream strmResult = new System.IO.MemoryStream ();
        imgResult.Save (strmResult, System.Drawing.Imaging.ImageFormat.Png);
        strmResult.Position = 0;
        streamList.Add (strmResult);
	}
	
    private Rectangle GetSelectedRectangle(Point firstPoint, Point secondPoint) {
		return new Rectangle(GetUpperLeftCorner(firstPoint, secondPoint),
        						GetRectangleSize(firstPoint, secondPoint));
    }

    private Point GetUpperLeftCorner(Point pt1, Point pt2) {
    	return new Point(Math.Min(pt1.X, pt2.X), Math.Min(pt1.Y, pt2.Y));
    }

    private Size GetRectangleSize(Point pt1, Point pt2) {
    	return new Size(Math.Abs(pt1.X - pt2.X), Math.Abs(pt1.Y - pt2.Y));
    }
	#endregion
	
	public void Dispose() {
		foreach (System.IO.MemoryStream strm in this.streamList) {
			if (strm != null)
				strm.Close();
		}
		
		ImgToSplit = null;
		this.streamList.Clear();
		this.streamList = null;
	}
}